﻿using System;
using System.Globalization;
using CuteRibs.MVVMLib;
using CuteRibs.WowArmory.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace CuteRibs.WowArmory.Models
{
	[JsonObject]
	public class Region
	{
		public static readonly Region Americas;
		public static readonly Region Europe;
		public static readonly Region Korea;
		public static readonly Region Taiwan;
		public static readonly Region China;

		static Region()
		{
			Americas = new Region("Americas", "us", "us.battle.net", AppRes.HostUS, "en", "es", "pt");
			Europe = new Region("Europe", "eu", "eu.battle.net", AppRes.HostEU, "en", "de", "es", "fr", "it", "pt", "ru");
			Korea = new Region("Korea", "kr", "kr.battle.net", AppRes.HostKR, "ko", "en");
			Taiwan = new Region("Taiwan", "tw", "tw.battle.net", AppRes.HostTW, "zh", "en");
			China = new Region("China", "cn", "www.battlenet.com.cn", AppRes.HostCN, "zh", "en");
		}

		public string Name { get; set; }
		public string Host { get; set; }
		public string Domain { get; private set; }
		public string DisplayName { get; set; }
		public string[] SupportedLocales { get; private set; }

		private Region(string name, string host, string domain, string displayName, params string[] locales)
		{
			this.Name = name;
			this.Host = host;
			this.Domain = domain;
			this.DisplayName = displayName;
			this.SupportedLocales = locales;
		}

		public override string ToString()
		{
			return string.Format("{0}: {1}", this.Name, this.Domain);
		}

		public string GetLocale()
		{
			var locale = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;

			if ((this == Region.Americas && !locale.In("en", "es", "pt"))
				|| (this == Region.Europe && !locale.In("en", "de", "es", "fr", "it", "pt", "ru"))
				|| (this == Region.Korea && !locale.In("ko", "en"))
				|| (this.In(Region.Taiwan, Region.China) && !locale.In("zh", "en")))
			{
				locale = "en";
			}

			return locale;
		}

		public static Region GetRegion(string name)
		{
			Region region;

			switch (name)
			{
				case "Europe":
					region = Europe;
					break;
				case "Korea":
					region = Korea;
					break;
				case "Taiwan":
					region = Taiwan;
					break;
				case "China":
					region = China;
					break;
				default:
					region = Americas;
					break;
			}

			return region;
		}
	}

	public class RegionConverter : DateTimeConverterBase
	{
		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var name = reader.Value as string;
			return Region.GetRegion(name);
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			var region = value as Region;
			writer.WriteValue(region.Name);
		}
	}
}
